import {selectTargetLibByPage} from '@/api/targetLib'
import {useLoading} from '@/hooks/loading'
import deepClone from '@/libs/deepClone'
import {checkIsPhone} from '@/libs/toolkit'
import {computed, defineComponent, PropType, reactive, watch} from 'vue'
import {CnMediumP, CnMediumSpan} from '../text'
import {DrawerContent, DrawerFooter} from './public'

const TargetLibImportDrawer = defineComponent({
  name: 'TargetLibImportDrawer',
  props: {
    title: {
      type: String,
      default: '指标库导入'
    },
    placement: {
      type: String as PropType<'top' | 'right' | 'bottom' | 'left'>,
      default: 'right'
    },
    visible: {
      type: Boolean,
      deafult: false
    }
  },
  emits: {
    'update:visible': (data: boolean): boolean => true,
    confirm: (data: Evaluation.PmGroupDimensionTarget[]): boolean => true
  },
  setup(props, {emit}) {
    const {loading, closeLoading, startLoading} = useLoading()
    let state = reactive<{
      visible: boolean
      allChecked: boolean
      checkedList: number[]
      pmTargetListSources: PmTargetLib.TargetLibData[]
      keyWord: string
    }>({
      visible: false,
      allChecked: false,
      checkedList: [],
      pmTargetListSources: [],
      keyWord: ''
    })

    const pmTargetList = computed(() =>
      state.pmTargetListSources.filter(item => item.targetLibName.indexOf(state.keyWord) !== -1)
    )

    const isPhone = computed(() => checkIsPhone())

    const checkedPmTarget = computed<Evaluation.PmGroupDimensionTarget[]>(() =>
      state.pmTargetListSources
        .filter(item => state.checkedList.indexOf(item.targetLibId) !== -1)
        .map(item => ({
          isBonus: item.isBonus,
          pmGroupDimensionTargetRange: item.targetLibRange,
          appointScoreSign: 0,
          appointUserDDId: undefined,
          makeProperty: undefined,
          pmGroupDimensionTargetId: -1,
          pmGroupDimensionTargetName: item.targetLibName,
          pmGroupDimensionId: -1,
          pmGroupDimensionTargetStand: item.targetLibStand,
          pmGroupDimensionTargetWeight: item.targetLibWeight,
          pmGroupDimensionTargetDesc: item.targetLibDesc,
          sort: 0,
          selfContentTem: item.selfContentTem ? item.selfContentTem : '',
          isMustSelect: item.isMustSelect
        }))
    )

    watch(
      () => props.visible,
      n => {
        state.visible = n
        if (n) {
          getDrawerData()
          console.log('打开指标库抽屉')
        } else {
          console.log('关闭指标库抽屉')
        }
      },
      {immediate: true, deep: true}
    )

    watch(
      () => state.visible,
      n => {
        emit('update:visible', n)
      }
    )

    watch(
      () => state.allChecked,
      n => {
        if (n) {
          state.checkedList = state.pmTargetListSources.map(item => item.targetLibId)
        } else {
          state.checkedList = []
        }
      }
    )

    /**重置选中状态 清空选中列表 */
    function resetCheckStatus() {
      state.allChecked = false
      state.checkedList = []
    }

    function getDrawerData() {
      startLoading()
      selectTargetLibByPage({page: 1, size: 999})
        .then(res => {
          state.pmTargetListSources = res.data.list
          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    function handleConfirmClick() {
      emit('confirm', deepClone(checkedPmTarget.value))
      resetCheckStatus()
      emit('update:visible', false)
    }

    return () => (
      <a-drawer
        v-model={[state.visible, 'visible']}
        title={props.title}
        placement={props.placement}
        width={isPhone.value ? '80%' : 500}
        onClose={() => {
          state.visible = false
        }}
      >
        <DrawerContent loading={loading.value}>
          <div class='w-full h-full overflow-hidden flex flex-col'>
            <div class='w-full h-80 flex flex-col justify-between'>
              <a-input
                class='w-full rounded-4'
                v-model={[state.keyWord, 'value']}
                placeholder='搜索指标'
                v-slots={{
                  prefix: () => <i class='iconfont icon-fangdajing text-infoHalf text-13'></i>
                }}
              ></a-input>
              <div class='w-full px-12 py-8 mb-8'>
                <a-checkbox class='custom-radio' v-model={[state.allChecked, 'checked']}>
                  全选
                </a-checkbox>
              </div>
            </div>
            <a-checkbox-group
              v-model={[state.checkedList, 'value']}
              class='w-full flex-1 overflow-y-auto'
            >
              {pmTargetList.value.map((item, idx) => (
                <label class='w-full h-80 border-t-1 border-infoLight px-12 py-12 m-0 flex gap-x-16 cursor-pointer'>
                  <a-checkbox class='custom-radio' value={item.targetLibId}></a-checkbox>
                  <div class='w-full h-full'>
                    <div>
                      <CnMediumSpan>{item.targetLibName}</CnMediumSpan>
                      <CnMediumSpan class='float-right'>{item.targetLibWeight}%</CnMediumSpan>
                    </div>
                    <div class='flex items-center gap-x-8 mt-12'>
                      <a-tag class='rounded-4' color='blue'>
                        {item.pmDimensionTypeName}
                      </a-tag>
                      {item.isBonus === 1 ? (
                        <a-tag class='rounded-4' color='blue'>
                          加分项
                        </a-tag>
                      ) : null}
                    </div>
                  </div>
                </label>
              ))}
            </a-checkbox-group>
          </div>
          <DrawerFooter>
            <div class='h-full flex items-center justify-between px-12'>
              <div class='h-full'></div>
              <div class='hfull flex items-center'>
                <a-button
                  class='rounded-l-4 rounded-r-0 border-r-0'
                  onClick={() => {
                    emit('update:visible', false)
                  }}
                >
                  取消
                </a-button>
                <a-button
                  type='primary'
                  class='rounded-r-4 rounded-l-0 border-l-0 bg-primary text-white'
                  onClick={handleConfirmClick}
                >
                  确认
                </a-button>
              </div>
            </div>
          </DrawerFooter>
        </DrawerContent>
      </a-drawer>
    )
  }
})
export default TargetLibImportDrawer
